<template>
    <view class="imgList" :class="[wrapClass]">
        <block v-for="(item, index) in imgUrlList" :key="index">
            <view
                class="imgItem"
                v-if="more ? index < line : true"
                :style="{
                  width: uploadWidth + 'rpx',
                  height: uploadHeight + 'rpx',
                  lineHeight: uploadHeight - 4 + 'rpx',
                  marginRight: line > 4 || (index + 1) % line != 0 ? '20rpx' : '0',
                }"
                @click.stop="lookImg(item, index)"
                @touchstart="onTouchStart"
                @touchend="onTouchEnd"
                @longtap="onLongTap(item, index)"
              >
                <image class="img" :src="item" mode="aspectFill" />
                <img
                  class="deleteImg"
                  @click.stop="deleteImg(index)"
                  :src="deleteImgUrl"
                  v-if="edit && showDelete"
                />

                <view
                  class="shade"
                  v-if="more && imgUrlList.length > line && index == line - 1"
                >
                    <view>更多</view>
                    <view>(共{{ imgUrlList.length }}张)</view>
                </view>
            </view>
        </block>
        <view
          class="addImg"
          :style="style"
          :class="{ showAdd: !noImgUrl }"
          v-if="edit && imgUrlList.length < imgCount"
          @click="addImg"
        >
            <img :src="noImgUrl" v-if="noImgUrl" :style="style" />
            <view class="before" :style="conputeAddBeforeStyle"></view>
            <view class="after" :style="conputeAddAfterStyle"></view>
            <view class="border"></view>
        </view>
        <preview-image
          :urls="imgUrlList"
          :current="current"
          ref="preview"
        ></preview-image>
    </view>
</template>

<script>
import conf from "@/common/config";
const imgBaseUrl = conf.imgBaseUrl;
const imgBaseUrlV2 = conf.imgBaseUrl + "icon_v2/";
import previewImage from "@/components/public/preview-image/preview-image";
import { mapState } from "vuex";
export default {
  components: {
    previewImage,
  },
  props: {
    imgList: {
      type: Array,
      default() {
        return [];
      },
    },
    imgCount: {
      type: [Number, String],
      default: 0,
    },
    uploadWidth: {
      type: Number,
      default: 220,
    },
    uploadHeight: {
      type: Number,
      default: 220,
    },
    uploadUrl: {
      type: String,
      default: conf.uploadUrl,
    },
    noImgUrl: {
      type: String,
      default: "",
    },
    deleteImgUrl: {
      type: String,
      default: imgBaseUrlV2 + "fankui_dle.png",
    },
    sourceType: {
      type: Array,
      default() {
        return ["album"];
      },
    },
    edit: {
      type: Boolean,
      default: true,
    },
    more: {
      default: false,
    },
    detail: {
      default: true,
    },
    showDelete: {
      default: true,
    },
    line: {
      default: 4,
    },
    wrapClass: {
      default: "",
    },
    longDelete: {
      default: false,
    },
  },
  data() {
    return {
      current: 0,
    };
  },
  methods: {
    deleteImg(index) {
      this.$emit("deleteImg", index);
    },
    async uploadImg(path = []) {
      uni.showLoading({ title: "" });
      let r = path.map((i) => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: this.uploadUrl,
            filePath: i,
            name: "file",
            header: {
              Authorization: "Bearer " + this.token,
            },
            success(response) {
              let res = response.data;
              if (typeof res !== "object") {
                try {
                  res = JSON.parse(response.data);
                } catch (e) {
                  res = null;
                  return reject(e);
                }
              }
              if (res.code === 200) {
                let data = res.data;
                if (typeof data !== "object") {
                  try {
                    data = JSON.parse(data);
                  } catch (e) {
                    data = {};
                  }
                }
                return data.path ? resolve(data.path) : reject(res);
              }

              return reject(res);
            },
            fail: (err) => reject(err),
          });
        });
      });
      let data = await Promise.all(r)
        .then((res) => res)
        .catch((err) => {
          console.log(err, "??err");
          return [];
        });
      uni.hideLoading();
      data.forEach((i) => {
        if (!i) return;
        let ret = i;
        if (this.detail) {
          ret = {
            url: i,
            name: i.substr(i.lastIndexOf(".") + 1),
            createDate: +new Date(),
            uid: +new Date(),
          };
        }
        this.$emit("uploadSuccess", ret);
      });
      // return r;
    },
    async addImg(index) {
      let _this = this;
      console.log(this.token, "??this.token");
      if (!this.token) {
        return uni.showToast({
          title: "请先登录!",
          icon: "none",
        });
      }
      uni.chooseImage({
        count: this.imgCount - this.imgList.length,
        sizeType: ["original", "compressed"],
        sourceType: this.sourceType,
        success(res) {
        console.log(res)
            
          _this.uploadImg(res.tempFilePaths);
        },
        fail(err) {
            
        }
      });
    },
    lookImg(url, index) {
      if (this.endTime && this.endTime - this.startTime >= 350) {
        return;
      }
      uni.previewImage({
        current: url, // 当前显示图片的http链接
        urls: this.imgUrlList, // 需要预览的图片http链接列表
      });
    },
    onTouchStart(e) {
      this.startTime = e.timeStamp;
    },
    onTouchEnd(e) {
      this.endTime = e.timeStamp;
    },
    onLongTap(item, index) {
      if (this.longDelete) {
        return uni.showModal({
          title: "提示",
          content: "确认删除该图片吗?",
          success: (res) => {
            if (res.confirm) {
              this.deleteImg(index);
              console.log("用户点击确定");
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      } else {
        this.$emit("longtap", item, index);
      }
    },
  },
  computed: {
    ...mapState("User", ["userInfo", "token"]),
    imgUrlList() {
      let imgUrlList = [];
      let imgList = this.imgList.map((i) => {
        return typeof i === "object" ? i.src || i.url : i;
      });
      imgList.forEach((item) => {
        if (item.indexOf("http") === -1) {
          item = item;
        }
        imgUrlList.push(item);
      });
      return imgUrlList;
    },
    conputeAddBeforeStyle() {
      let w = this.uploadWidth;
      let h = this.uploadHeight;
      if (w < 140 || h < 140) {
        let t = Math.min(h, w);
        let r = t * 0.5;
        return `width: ${r}rpx; height: 6rpx`;
      }
    },
    conputeAddAfterStyle() {
      let w = this.uploadWidth;
      let h = this.uploadHeight;
      if (w < 140 || h < 140) {
        let t = Math.min(h, w);
        let r = t * 0.5;
        return `height: ${r}rpx; width: 6rpx`;
      }
    },
    style() {
      return `width: ${this.uploadWidth + "rpx"};height: ${
        this.uploadHeight + "rpx"
      };line-height: ${this.uploadHeight - 2 + "rpx"};`;
    },
  },
};
</script>

<style scoped lang="stylus">
@import '~@/common/stylus/mixins';

.imgList {
  display: flex;
  width: 100%;
  flex-wrap: wrap;

  &.line {
    flex-wrap: nowrap;
  }

  &.right {
    justify-content: flex-end;
  }

  .addImg {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;

    &:after, &:before {
      position: absolute;
      content: '';
      width: 100%;
      height: 100%;
      background-image: linear-gradient(to right, #ccc 0%, #ccc 50%, transparent 50%);
      background-size: 16rpx 2rpx;
      background-repeat: repeat-x;
    }

    &:before {
      background-position: left bottom;
    }

    >.border {
      position: absolute;
      width: 100%;
      height: 100%;

      &:after, &:before {
        position: absolute;
        content: '';
        width: 100%;
        height: 100%;
        left: 0;
        background-image: linear-gradient(180deg, #ccc 0%, #ccc 50%, transparent 50%);
        background-size: 2rpx 16rpx;
        background-repeat: repeat-y;
        background-position: left top;
      }

      &:before {
        background-position: right top;
      }
    }

    &.showAdd {
      >.after, >.before {
        position: absolute;
        content: '';
        width: 52rpx;
        height: 52rpx;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        background: #D4D4D4;
      }

      >.before {
        height: 4rpx;
      }

      >.after {
        width: 4rpx;
      }
    }
  }

  .imgItem, .addImg {
    position: relative;
    // border: 3rpx dashed #eee;
    text-align: center;
    color: #eee;
    font-size: 100rpx;
    font-weight: 100;
    margin-bottom: 20rpx;
    // overflow: hidden;
    // background: #F6F6F6;
    border-radius: 10rpx;
  }

  .imgItem {
    position: relative;
    z-index: 1;
    display: flex;
    margin-right: 20rpx;
    align-items: center;
    justify-content: center;

    .shade {
      position: absolute;
      z-index: 3;
      display: flex;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.3);
      color: #fff;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      line-height: 40rpx;
      flex-direction: column;
      font-weight: 500;
    }

    .img {
      position: relative;
      z-index: 1;
      width: 100%;
      max-width: 100%;
      max-height: 100%;
    }
  }

  .deleteImg {
    position: absolute;
    z-index: 8;
    width: 42rpx !important;
    height: 40rpx !important;
    right: -21rpx;
    top: -20rpx;
    extend-click();
    position: absolute;
  }
}
</style>
